package labuladong.leetcode.editor.cn._01linkedlist.ch00;

import labuladong.leetcode.editor.cn._00utils.LinkedListUtils;
import labuladong.leetcode.editor.cn._00bean.ListNode;

import static labuladong.leetcode.editor.cn._00utils.LinkedListUtils.build;

public class _21_MergeTwoSortedLists {

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            // 虚拟头结点
            ListNode dummy = new ListNode(-1), p = dummy;
            ListNode p1 = l1, p2 = l2;

            while (p1 != null && p2 != null) {
                // 比较 p1 和 p2 两个指针
                // 将值较小的的节点接到 p 指针
                if (p1.val > p2.val) {
                    p.next = p2;
                    p2 = p2.next;
                } else {
                    p.next = p1;
                    p1 = p1.next;
                }
                // p 指针不断前进
                p = p.next;
            }

            if (p1 != null) {
                p.next = p1;
            }

            if (p2 != null) {
                p.next = p2;
            }
            return dummy.next;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new _21_MergeTwoSortedLists().new Solution();

        int[] nums1 = {1, 2, 4};
        ListNode link1 = build(nums1);
        LinkedListUtils.print(link1);

        int[] nums2 = {1, 3, 4};
        ListNode link2 = build(nums2);
        LinkedListUtils.print(link2);

        ListNode res = solution.mergeTwoLists(link1, link2);
        LinkedListUtils.print(res);
    }
}
